package com.shangjinrong.controller.site;

import com.alibaba.fastjson.JSON;
import com.shangjinrong.domain.LendReturn;
import com.shangjinrong.hfb.RequestHelper;
import com.shangjinrong.result.R;
import com.shangjinrong.service.LendReturnService;
import com.shangjinrong.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author Naruto
 */

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("site/lendReturn")
public class SiteLendReturnController {


    @Autowired
    private LendReturnService lendReturnService;

    @GetMapping("getLendReturnByLendId/{id}")
    public R getLendReturnByLendId(@PathVariable Long id) {
        List<LendReturn> lendReturnList = lendReturnService.getByLendId(id);

        return R.ok().data("lendReturnList", lendReturnList);
    }

    /**
     * 还款
     *
     * @param lendReturnId 标的还款id
     * @return 表单页面
     */
    @PostMapping("commitReturn/{lendReturnId}")
    public R commitReturn(@PathVariable Long lendReturnId, HttpServletRequest request) {
        String token = request.getHeader("token");

        Long userId = JwtUtils.getUserId(token);

        String formStr = lendReturnService.commitReturn(lendReturnId, userId);

        return R.ok().data("formStr", formStr);
    }


    @PostMapping("notifyUrl")
    public String notifyUrl(HttpServletRequest request) {
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
        log.info("还款异步回调:{}", JSON.toJSONString(paramMap));

        //签名校验
        if (RequestHelper.isSignEquals(paramMap)) {
            if ("0001".equals(paramMap.get("resultCode"))) {
                lendReturnService.notify(paramMap);
            } else {
                log.info("还款异步回调失败：" + JSON.toJSONString(paramMap));
                return "fail";
            }
        } else {
            log.info("还款异步回调签名错误：" + JSON.toJSONString(paramMap));
            return "fail";
        }
        return "success";
    }
}

